<?php
if (!$is_success) {
    $dp = new jDatePicker();
    $dp->__dateFormat = "yy-mm-dd";
    echo "<scr" . "ipt type=\"text/javascript\">";
    $dp->generateDP("tanggal_po");
    echo "</scr" . "ipt>";
    $dp->init();
    ?>
    <script type="text/javascript">
        jQuery.ajaxSetup({async: false});

        function _obj_fSendValue(kode, nama, elmKode, elmNama) {
            var elmk = document.getElementById("" + elmKode + "");
            var elmn = document.getElementById("" + elmNama + "");
            try {
                if(elmk.value == "")
                    elmk.value = kode;
                else
                    elmk.value = elmk.value + "," + kode;

                if(elmn.value == "")
                    elmn.value = nama;
                else
                    elmn.value = elmn.value + "\n" + nama;

                jQuery.ajax({
                    type: "POST",
                    url : "<?php echo site_url('popup/get_customer_detil_2') ?>" ,
                    data: {kode: kode},
                    success: function(msg){
                        var result = jQuery.parseJSON(msg);
                        jQuery("#nama_customer").val(result.nama_customer);
                        jQuery("#id_customer").val(result.id_customer);
                        jQuery("#alamat_detail_customer").val(result.alamat_detail_customer);
                        jQuery("#alamat_komplit").val(result.alamat_komplit);
                        jQuery("#kontak_komplit").val(result.kontak_komplit);
                        jQuery("#attendance").val(result.attendance);
                    },
                    error: function(msg){
                        alert(msg);
                    }
                });
            }
            catch(e) {
                alert(e.message);
            }
        }

        function init_item(quot){
            jQuery.ajax({
                type: "POST",
                url : "<?php echo site_url('popup/get_quotation_item') ?>",
                data: {quot: quot},
                success: function(msg){            
                    var result = jQuery.parseJSON(msg);

                    for(var i = 0; i < result.length; i++)
                        append_table(result[i]);
                },
                error: function(msg){
                    alert(msg);
                }
            });
        }

        function append_table(result){
            var length = jQuery("#tablebody").find("tr").length;

            if(length == 1){
                jQuery("#no_item").hide();
            }

            jQuery("#tablebody").append(
            '<tr class="GridItem1">\n'+
                '<td>'+length+'<input type="hidden" name="id_item[]" value="'+result.item+'" /><input type="hidden" name="satuan_beli[]" value="'+result.satuan+'" /></td>\n'+
                '<td><input type="text" name="nama_item[]" value="'+result.nama+'" /></td>\n'+
                '<td><input onblur="UpdateTotals(' + length + ');" type="text" name="quantity[]" value="'+result.qty+'" / id=qty_' + length + '> '+result.satuan+'</td>\n'+
                '<td class="IDR" align="right"><input type=text name="harga_beli[]" id=harga_beli_' + length + ' value="'+result.harga_beli+'"></td>\n'+    
                '<td class="IDR" align="right"><input type=text name="harga_jual[]" id=harga_jual_' + length + ' value="'+result.price+'"></td>\n'+
                '<td class="IDR" align="right"><span class=total style="float: right;" id=total_' + length + '>'+formatNumber(result.total)+'</span></td>\n'+
                '<td class="USD" align="right"><input type=text name="harga_beli_dollar[]" id=harga_beli_dollar_' + length + ' value="'+result.harga_beli_dollar+'"></td>\n'+
                '<td class="USD" align="right"><input type=text name="harga_jual_dollar[]" id=harga_jual_dollar_' + length + ' value="'+result.priced+'"></td>\n'+
                '<td class="USD" align="right"><span class=total_dollar style="float: right;" id=total_dollar_' + length + '>'+(result.totald)+'</span></td>\n'+
                '<td><input type=checkbox name=selected[] checked=checked value='+result.item+' onclick="update_price(this, this.checked);" /></td>'+
                '</tr>'
        );

            jQuery("#total").html(parseFloat(jQuery("#total").html()) + parseFloat(result.total));
            jQuery("#totald").html(parseFloat(jQuery("#totald").html()) + parseFloat(result.totald));

            updateCrcSymbol();
            ReFormat();
        }

        function UpdateTotals(id) {
            var qty = jQuery("#qty_" + id).val();
            var harga_jual = jQuery("#harga_jual_" + id).val();
            harga_jual = harga_jual.replace(/\./gi,"");
            jQuery("#total_" + id).html(formatNumber(parseFloat(qty) * parseFloat(harga_jual)));

            var harga_jual_dollar = jQuery("#harga_jual_dollar_" + id).val();
            harga_jual_dollar = harga_jual_dollar.replace(/\./gi,"").replace(/\,/gi,".");
            var total = parseFloat(qty) * parseFloat(harga_jual_dollar);
            jQuery("#total_dollar_" + id).html(total.toString().replace(/\./gi,","));

            CalculateTotal();
        }


        function CalculateTotal() {
            var totals = jQuery('.total');
            var grandTotal = 0;
            jQuery.each(totals, function(i) {
                grandTotal += parseFloat(jQuery(totals[i]).html().replace(/\./gi,""));
            });
            jQuery('#total').html(parseFloat(grandTotal));

            var totals = jQuery('.total_dollar');
            var grandTotal = 0;
            jQuery.each(totals, function(i) {
                grandTotal += parseFloat(jQuery(totals[i]).html().replace(/\./gi,"").replace(/\,/gi,"."));
            });
            jQuery('#totald').html(grandTotal);

            ReFormat();
        }

        function ReFormat(){
            try{
                jQuery(".shou").each(function(){
                    jQuery("#"+this.id+"_show").html(formatNumber(parseFloat(jQuery(this).html()), 2));
                });
            }catch(e){
                alert(e);
            }
        }

        function update_price(elm, checked){
            var tr_parent = jQuery(elm).parent().parent();
            var td_total = jQuery(tr_parent).find("td").toArray();
            var total_deleted = parseFloat(jQuery(td_total[4]).first().contents().filter(function(){
                return this.nodeType == Node.TEXT_NODE;
            }).text().replace(/[^\d]/,''));
            var totald_deleted = parseFloat(jQuery(td_total[6]).first().contents().filter(function(){
                return this.nodeType == Node.TEXT_NODE;
            }).text().replace(/[^\d]/,''));

            if(checked){
                jQuery("#total").html(parseFloat(jQuery("#total").html()) + parseFloat(total_deleted));
                jQuery("#totald").html(parseFloat(jQuery("#totald").html()) + parseFloat(totald_deleted));
                jQuery(tr_parent).addClass("GridItem1");
            } else {
                jQuery("#total").html(parseFloat(jQuery("#total").html()) - parseFloat(total_deleted));
                jQuery("#totald").html(parseFloat(jQuery("#totald").html()) - parseFloat(totald_deleted));
                jQuery(tr_parent).removeClass("GridItem1");
            }

            ReFormat();
        }

        function set_element(is_read_only){
            if(is_read_only){
                jQuery("#nama_customer").addClass("read-only");
                jQuery("#alamat_detail_customer").addClass("read-only");
                jQuery("#alamat_komplit").addClass("read-only");
                jQuery("#kontak_komplit").addClass("read-only");
                jQuery("#attendance").addClass("read-only");
            } else {
                jQuery("#nama_customer").removeClass("read-only");
                jQuery("#alamat_detail_customer").removeClass("read-only");
                jQuery("#alamat_komplit").removeClass("read-only");
                jQuery("#kontak_komplit").removeClass("read-only");
                jQuery("#attendance").removeClass("read-only");

                jQuery("#list_quotation_id").val("");
                jQuery("#list_quotation_number").val("");
                jQuery("#nama_customer").val("");
                jQuery("#alamat_detail_customer").val("");
                jQuery("#alamat_komplit").val("");
                jQuery("#kontak_komplit").val("");
                jQuery("#attendance").val("");
                jQuery("#id_customer").val("");

                jQuery("#tablebody").find("tr").each(function(){
                    if(this.id != "no_item")
                        jQuery(this).remove();
                });

                jQuery("#no_item").show();
                jQuery("#total").html(0);
            }

            jQuery("#nama_customer").attr("readonly", is_read_only);
            jQuery("#alamat_detail_customer").attr("readonly", is_read_only);
            jQuery("#alamat_komplit").attr("readonly", is_read_only);
            jQuery("#kontak_komplit").attr("readonly", is_read_only);
            jQuery("#attendance").attr("readonly", is_read_only);
        }

        function setBlnToRome(bln){
            if(bln=="01"){
                return "I";
            }else if(bln=="02"){
                return "II";
            }else if(bln=="03"){
                return "III";
            }else if(bln=="04"){
                return "IV";
            }else if(bln=="05"){
                return "V";
            }else if(bln=="06"){
                return "VI";
            }else if(bln=="07"){
                return "VII";
            }else if(bln=="08"){
                return "VIII";
            }else if(bln=="09"){
                return "IX";
            }else if(bln=="10"){
                return "X";
            }else if(bln=="11"){
                return "XI";
            }else{
                return "XII";
            }
        }

        function setPurchaseNumber(){
            var prefix = <?php echo json_encode($prefix); ?>;

            var date = (jQuery("#tanggal_po").val()).toString();
            var partsArray = date.split('-');
            var tgl = partsArray[2];
            var bln = setBlnToRome(partsArray[1]);
            var thn =  partsArray[0];
            var no= prefix + "/ADL/PO/" + tgl +"/" + bln +"/" +thn;
            jQuery("#nomor_po").val(no);

        }

        function updateCrcSymbol(){
            var symbol = jQuery("#curency").val();
            if(symbol=="IDR") {
                jQuery(".IDR").show();
                jQuery(".USD").hide();
            }else{
                jQuery(".IDR").hide();
                jQuery(".USD").show();
            }
        }

        function append_diskon(val){
            jQuery("#diskon").val(parseInt(jQuery("#diskon").val()) + parseInt(val));
        }

        function close_gb(){
    <?php echo CloseGB(true); // close greybox    ?>
                }

                function download_item(file){
                    window.open('<?php echo base_url("import"); ?>/'+file, '_blank');
                }

                function formatNumber (obj, decimal) {
                    //decimal  - the number of decimals after the digit from 0 to 3
                    //-- Returns the passed number as a string in the xxx,xxx.xx format.
                    anynum = eval(obj);
                    divider =10;
                    switch(decimal){
                        case 0:
                            divider =1;
                            break;
                        case 1:
                            divider =10;
                            break;
                        case 2:
                            divider =100;
                            break;
                        default:       //for 3 decimal places
                            divider =1000;
                    }

                    workNum=Math.abs((Math.round(anynum*divider)/divider));
                    workStr=""+workNum
                    if (workStr.indexOf(",")==-1){workStr+=","}
                    dStr=workStr.substr(0,workStr.indexOf(","));
                    dNum=dStr-0
                    pStr=workStr.substr(workStr.indexOf(","))

                    while (pStr.length-1< decimal){
                        pStr+="0"
                    }

                    if(pStr ==',') pStr ='';
                    //--- Adds a comma in the thousands place.
                    if (dNum>=1000) {
                        dLen=dStr.length
                        dStr=parseInt(""+(dNum/1000))+"."+dStr.substring(dLen-3,dLen)
                    }
                    //-- Adds a comma in the millions place.
                    if (dNum>=1000000) {
                        dLen=dStr.length
                        dStr=parseInt(""+(dNum/1000000))+"."+dStr.substring(dLen-7,dLen)
                    }

                    retval = dStr + pStr
                    //-- Put numbers in parentheses if negative.
                    if (anynum<0) {retval="("+retval+")";}
                    //You could include a dollar sign in the return value.
                    //retval =  "$"+retval
                    return retval;
                }
    </script>
    <style>
        .shou{
            display: none;
        }
    </style>

    <h3 class="title-popup">Form Tambah Purchase Order</h3>

    <div style="padding:10px">

        <?php if ($error != "") { ?>
            <div class="BoxMessage Warning">Proses Gagal, <br /><?php echo $error; ?></div>
        <?php } ?>

        <div id="content">
            <div class="DivTable">
                <?php
                echo form_open_multipart();

                $list_quotation_number = array();
                $list_quotation_id = array();

                if (is_object($list_quotation)) {
                    foreach ($list_quotation->result() as $row) {
                        $list_quotation_id[] = $row->id_quotation;
                        $list_quotation_number[] = $row->nomor_quotation;
                    }
                }

                $list_quotation_id = implode(",", $list_quotation_id);
                $list_quotation_number = implode("\n", $list_quotation_number);
                ?>
                <table>
                    <tr>
                        <td>Date</td>
                        <td>:</td>
                        <td><?php echo form_input(array("name" => "tanggal_po", "id" => "tanggal_po", "class" => "input_text", "readonly" => "readonly", "size" => 47), $tanggal_po); ?></td>
                        <td>&nbsp;</td>
                        <td>&nbsp;&nbsp;&nbsp;</td>
                        <td>File PO</td>
                        <td>:</td>
                        <td>
                            <?php
                            echo form_input(array("name" => "file_upload", "id" => "file_upload", "type" => "file", "class" => "input_file", "size" => 10));
                            echo "&nbsp;";
                            if (!empty($file_attachment_po)) {
                                echo '<a href="#" onclick="download_item(\'' . $file_attachment_po . '\')" title="download"><img src="' . base_url("style/layout/images/icons/arrow_down.png") . '"/>Download</a>';
                            }
                            ?>
                        </td>
                    </tr>
                    <tr>
                        <td>List Quotation Number</td>
                        <td>:</td>
                        <td>
                            <?php echo form_textarea(array("name" => "list_quotation_number", "id" => "list_quotation_number", "rows" => 2, "cols" => 37, "readonly" => "readonly", "class" => "read-only"), $list_quotation_number); ?>
                            <input type="hidden" name="list_quotation_id" id="list_quotation_id" value="<?php echo $list_quotation_id; ?>"   />
                        </td>
                        <td>
                            <?php echo $gbquote ?>
                            <a class="clear" onclick="set_element(false);" title="Clear Choice"><span></span></a>
                            <a class="help" onclick="alert('Berisi daftar nomor quotation. Dipisahkan oleh tanda enter');" title="Dapatkan customer"><span></span></a>
                        </td>
                        <td>&nbsp;&nbsp;&nbsp;</td>
                        <td>PO Note</td>
                        <td>:</td>
                        <td><?php echo form_textarea(array("name" => "catatan_po", "id" => "catatan_po", "class" => "input_text", "rows" => 2, "cols" => 37), $catatan_po); ?></td>
                    </tr>
                    <tr>
                        <td>Requester</td>
                        <td>:</td>
                        <td>
                            <input type="text" name="nama_customer" id="nama_customer" value="<?php echo $nama_customer; ?>" maxlength="50" size="50" />
                            <input type="hidden" name="id_customer" id="id_customer" value="<?php echo $id_customer; ?>"   />
                        </td>
                        <td>&nbsp;</td>
                        <td>&nbsp;&nbsp;&nbsp;</td>
                        <td>PO NO</td>
                        <td>:</td>
                        <td><?php echo form_input(array("name" => "nomor_po", "id" => "nomor_po", "size" => "50"), $nomor_po); ?></td>
                    </tr>
                    <tr>
                        <td>Address</td>
                        <td>:</td>
                        <td><?php echo form_input(array("name" => "alamat_detail_customer", "id" => "alamat_detail_customer", "size" => 50), $alamat_detail_customer); ?></td>
                    </tr>
                    <tr>
                        <td>Full Address</td>
                        <td>:</td>
                        <td>
                            <?php echo form_textarea(array("name" => "alamat_komplit", "id" => "alamat_komplit", "class" => "input_text", "rows" => 2, "cols" => 37), $alamat_komplit); ?>
                        </td>
                        <td>
                            <a class="help" onclick="alert('Berisi alamat lengkap, kota, kodepos. Dipisahkan oleh tanda enter');" title="Petunjuk"><span></span></a>
                        </td>
                    </tr>
                    <tr>
                        <td>Phone/Fax/Email</td>
                        <td>:</td>
                        <td>
                            <?php echo form_input(array("name" => "kontak_komplit", "id" => "kontak_komplit", "class" => "input_text", "size" => 50), $kontak_komplit); ?>
                        </td>
                        <td>
                            <a class="help" onclick="alert('Berisi no telepon, fax, dan email. Dipisahkan oleh tanda /');" title="Petunjuk"><span></span></a>
                        </td>
                    </tr>
                    <tr>
                        <td>Currency</td>
                        <td>:</td>
                        <td>
                            <?php
                            if ($using_dollar_currency == 1) {
                                $crc = "USD";
                            } else {
                                $crc = "IDR";
                            }
                            ?>
                            <select id="curency" name="crc" onchange="updateCrcSymbol()" value="<?php echo $crc; ?>">
                                <option value="<?php echo $crc; ?>"><?php echo $crc; ?></option>
                                <option value="USD">USD</option>
                                <option value="IDR">IDR</option>
                            </select>
                        </td>
                        <td>&nbsp;</td>
                        <td>&nbsp;&nbsp;&nbsp;</td>
                        <td>Diskon</td>
                        <td>:</td>
                        <td><?php echo form_input(array("name" => "diskon", "id" => "diskon", "size" => 50), $diskon, "onkeyup=\"this.value=this.value.replace(/[^\d]/,'');\""); ?></td>
                    </tr>
                </table>
                <br/>

                <?php echo $gbitem; ?>

                <br/><br/>

                <table class="GridTable" style="width: 100%;">
                    <thead>
                        <tr class="GridHeader">
                            <td>No.</td>
                            <td>Description</td>
                            <td>Qty</td>
                            <td class="IDR">Harga Beli</td>
                            <td class="IDR">Harga Jual</td>
                            <td class="IDR">Total</td>
                            <td class="USD">Harga Beli</td>
                            <td class="USD">Harga Jual</td>
                            <td class="USD">Total Dollar</td>
                            <td width="5%">Action</td>
                        </tr>
                    </thead>
                    <tbody id="tablebody">
                        <tr class="GridItem1" id="no_item">
                            <td colspan="8">Tidak ada data</td>
                        </tr>
                        <?php
                        $total_harga = 0;
                        $totald_harga = 0;
                        if (is_object($item)) {
                            if ($item->num_rows() > 0) {
                                $nomor = 1;
                                foreach ($item->result() as $row) {
                                    ?>
                                    <tr class="GridItem1">
                                        <td><?php echo $nomor; ?></td>
                                        <td><input type="text" name="nama_item[]" value="<?php echo $row->nama_item ?>" /><input type="hidden" name="id_item[]" value="<?php echo $row->id_item ?>" /><input type="hidden" name="satuan_beli[]" value="<?php echo $row->satuan_beli ?>" /></td>
                                        <td><input type="text" name="quantity[]" onblur="UpdateTotals('<?php echo $nomor; ?>');" value="<?php echo $row->quantity ?>" id="qty_<?php echo $nomor; ?>"/><?php echo $row->satuan_beli ?></td>
                                        <td class="IDR" align="right"><input type="text" name="harga_beli[]" id="harga_beli_<?php echo $nomor; ?>" value="<?php echo $row->harga_beli ?>"></td>
                                        <td class="IDR" align="right"><input type="text" name="harga_jual[]" id="harga_jual_<?php echo $nomor; ?>" value="<?php echo $row->harga_jual ?>"></td>
                                        <td class="IDR" align="right"><span class=total style="float: right;" id="total_<?php echo $nomor; ?>"><?php echo number_format($row->harga_jual * $row->quantity, 0, ',', '.') ?></span></td>
                                        
                                        <td class="USD" align="right"><input type="text" name="harga_beli_dollar[]" id="harga_beli_dollar_<?php echo $nomor; ?>" value="<?php echo $row->harga_beli_dollar ?>"></td>
                                        <td class="USD" align="right"><input type="text" name="harga_jual_dollar[]" id="harga_jual_dollar_<?php echo $nomor; ?>" value="<?php echo $row->harga_jual_dollar ?>"></td>
                                        <td class="USD" align="right"><span class=total_dollar style="float: right;" id="total_dollar_<?php echo $nomor; ?>"><?php echo number_format($row->harga_jual_dollar * $row->quantity, 2, ',', '.') ?></span></td>
                                        <td><input type=checkbox name=selected[] checked=checked value='<?php echo $row->id_item ?>' onclick="update_price(this, this.checked);" /></td>
                                    </tr>
                                    <?php
                                    $total_harga += $row->harga_jual * $row->quantity;
                                    $totald_harga += $row->harga_jual_dollar * $row->quantity;
                                    $nomor++;
                                }

                                echo "<script>jQuery(\"#no_item\").hide();</script>";
                            }
                        }
                        ?>
                    </tbody>
                    <tfoot>
                        <tr class="GridHeader">
                            <td colspan="3" align="right">Total</td>
                            <td class="IDR">&nbsp;</td>
                            <td class="IDR" align="right"><span style="float: left;"></span><span id="total" class='shou'><?php echo $total_harga ?></span><span id="total_show">0</span></td>
                            <td class="USD">&nbsp;</td>
                            <td class="USD" align="right"><span style="float: left;"></span><span id="totald" class='shou'><?php echo $totald_harga ?></span><span id="totald_show">0</span></td>
                            <td>&nbsp;</td>
                    <script>updateCrcSymbol();ReFormat();</script>
                    </tr>
                    </tfoot>
                </table>
                <br/><br/>

                <?= form_submit(array("name" => "btnSubmit", "class" => "CommandButton"), "Save") ?>
                <?= form_button(array("class" => "CommandButton"), "Cancel", "onclick='close_gb();'") ?>
                <?= form_close() ?>

            </div>
        </div>
    </div>
<?php } else { ?>
    <script type='text/javascript'>
        function close_gb(){
    <?php echo CloseGB(true); // close greybox    ?>
                }
    </script>

    <div style="padding-top: 25%;">
        <div class="BoxMessage">Proses Berhasil, apakah anda mau membuat INVOICE?<br /><?php echo $error; ?></div>

        <div id="box-control-save">
            <?= form_button(array("class" => "CommandButton"), "Ya", "onclick=\"window.open('" . site_url("transaksi/invoice_add?po=$kode") . "', '_blank');" . reloadParent() . "\"") ?>&nbsp;
            <?= form_button(array("class" => "CommandButton"), "Tidak", "onclick='close_gb();'") ?>
        </div>
    </div>
<?php } ?>